'use client'

import { useEffect, useState } from 'react';
import { ISSUE_STATE, ISSUE_TYPE, IssueInfo } from '@/grpc/types';
import { getStateColor, issueState } from '@/utils/issue_utils';
import { Card, Descriptions, Space } from 'antd';
import type { Task as GanttTask } from 'gantt-task-react';
import moment from 'moment';
import { Gantt, ViewMode, } from 'gantt-task-react';
import "gantt-task-react/dist/index.css";

type ExtGanttTask = GanttTask & {
    issue: IssueInfo;
};

function TooltipContent(props: {
    task: GanttTask;
    fontSize: string;
    fontFamily: string;
}) {
    const renderState = (val: ISSUE_STATE) => {
        const v = issueState[val];
        return (
            <div
                style={{
                    background: `rgb(${getStateColor(val)} / 20%)`,
                    width: '50px',
                    margin: '0 auto',
                    borderRadius: '50px',
                    textAlign: 'center',
                    color: `rgb(${getStateColor(val)})`,
                }}
            >
                {v?.label}
            </div>
        );
    };

    return (
        <>
            {props.task.type != "project" && (



                <div style={{ backgroundColor: "white", padding: "10px 10px", border: "1px solid #e4e4e8" }}>
                    <Descriptions title={`${(props.task as ExtGanttTask).issue.issueType == ISSUE_TYPE.ISSUE_TYPE_TASK ? "任务" : "缺陷"}:${(props.task as ExtGanttTask).issue.basicInfo?.title}`} bordered={true}>
                        <Descriptions.Item label="阶段">{renderState((props.task as ExtGanttTask).issue.state!)}</Descriptions.Item>
                        <Descriptions.Item label="预估时间">
                            <span style={{ color: (props.task as ExtGanttTask).issue.hasEstimateMinutes ? undefined : "red" }}>
                                {(props.task as ExtGanttTask).issue.hasEstimateMinutes ? `${((props.task as ExtGanttTask).issue.estimateMinutes! / 60).toFixed(1)}小时` : "未设置"}
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label="剩余时间">
                            <span style={{ color: (props.task as ExtGanttTask).issue.hasRemainMinutes ? undefined : "red" }}>
                                {(props.task as ExtGanttTask).issue.hasRemainMinutes ? `${((props.task as ExtGanttTask).issue.remainMinutes! / 60).toFixed(1)}小时` : "未设置"}
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label="预估开始时间">
                            <span style={{ color: (props.task as ExtGanttTask).issue.hasStartTime ? undefined : "red" }}>
                                {(props.task as ExtGanttTask).issue.hasStartTime ? moment((props.task as ExtGanttTask).issue.startTime!).format("YYYY-MM-DD") : "未设置"}
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label="预估结束时间">
                            <span style={{ color: (props.task as ExtGanttTask).issue.hasEndTime ? undefined : "red" }}>
                                {(props.task as ExtGanttTask).issue.hasEndTime ? moment((props.task as ExtGanttTask).issue.endTime).format("YYYY-MM-DD") : "未设置"}
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label="截止时间">
                            {(props.task as ExtGanttTask).issue.hasDeadLineTime == true && moment((props.task as ExtGanttTask).issue.deadLineTime).format("YYYY-MM-DD")}
                        </Descriptions.Item>
                        <Descriptions.Item label="创建者">{(props.task as ExtGanttTask).issue.createDisplayName}</Descriptions.Item>
                        <Descriptions.Item label="执行者">
                            <span style={{ color: (props.task as ExtGanttTask).issue.execUserId == "" ? "red" : undefined }}>
                                {(props.task as ExtGanttTask).issue.execUserId == "" ? "未设置" : (props.task as ExtGanttTask).issue.execDisplayName}
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label="检查者">{(props.task as ExtGanttTask).issue.checkDisplayName}</Descriptions.Item>
                    </Descriptions>
                </div>
            )}
        </>
    );
}

export interface GanttPanelProps {
    spritName: string;
    startTime: number;
    endTime: number;
    issueInfoList: IssueInfo[];
}

export function GanttPanel(props: GanttPanelProps) {
    const [taskList, setTaskList] = useState<GanttTask[]>([]);

    const calcName = (issue: IssueInfo): string => {
        const parts: string[] = [`状态:${issueState[issue.state!].label}`];
        if (issue.execDisplayName != "") {
            parts.push("执行者:" + issue.execDisplayName);
        }
        if (issue.checkDisplayName != "") {
            parts.push("检查者:" + issue.checkDisplayName)
        }
        return `${issue.issueType == ISSUE_TYPE.ISSUE_TYPE_TASK ? "任务" : "缺陷"}:${issue.basicInfo?.title}(${parts.join(",")})`;
    }

    useEffect(() => {
        if (props.issueInfoList.length == 0) {
            return;
        }
        const tmpList: ExtGanttTask[] = [];
        let totalEstimate = 0;
        let totalRemain = 0;
        for (const issue of props.issueInfoList) {
            const startTime = (issue.hasStartTime ? issue.startTime : props.startTime) ?? 0;
            const endTime = (issue.hasEndTime ? issue.endTime : props.endTime) ?? 0;
            let progress = 0;
            if (issue.hasRemainMinutes && issue.hasEstimateMinutes) {
                progress = Math.floor((1 - issue.remainMinutes! / issue.estimateMinutes!) * 100);
            }
            tmpList.push({
                id: issue.issueId!,
                type: "task",
                name: calcName(issue),
                start: moment(startTime).startOf("day").toDate(),
                end: moment(endTime).endOf("day").toDate(),
                progress: progress,
                styles: {
                    backgroundColor: (issue.hasStartTime && issue.hasEndTime && issue.hasRemainMinutes && issue.hasEstimateMinutes) ? "forestgreen" : "crimson",
                    backgroundSelectedColor: "gold",
                },
                issue: issue,
            });
            if (issue.hasEstimateMinutes) {
                totalEstimate += issue.estimateMinutes!;
            }
            if (issue.hasRemainMinutes) {
                totalRemain += issue.remainMinutes!;
            }
        }

        let progress = 0;
        if (totalEstimate > 0) {
            progress = Math.floor((1 - totalRemain / totalEstimate) * 100);
        }
        const spritTask: GanttTask = {
            id: props.spritName,
            type: "project",
            name: `${props.spritName}(${moment(props.startTime).format("YYYY-MM-DD")}至${moment(props.endTime).format("YYYY-MM-DD")})`,
            start: moment(props.startTime).startOf("day").toDate(),
            end: moment(props.endTime).endOf("day").toDate(),
            progress: progress,
        };
        setTaskList([spritTask, ...tmpList]);
    }, []);

    return (
        <Card title="甘特图" headStyle={{ backgroundColor: "#eee" }}
            bodyStyle={{ width: "100%", overflowX: "scroll" }}
            extra={
                <Space style={{ fontSize: "14px", fontWeight: 600 }}>
                    <div>图例说明:</div>
                    <div style={{ backgroundColor: "forestgreen", padding: "4px 8px", borderRadius: "6px" }}>参数正常</div>
                    <div style={{ backgroundColor: "crimson", padding: "4px 8px", borderRadius: "6px" }}>参数异常</div>
                </Space>
            }>
            {taskList.length > 0 && (
                <Gantt tasks={taskList} viewMode={ViewMode.Day} locale="chi" listCellWidth="" columnWidth={100} TooltipContent={TooltipContent}
                    rowHeight={36} rtl={false} preStepsCount={2} ganttHeight={500} />
            )}
        </Card>
    );
}
